#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project:     rest_flask
# @File:        data_set_api.py
# @Author:      Fan GuiChuan
# @Date:        2025/7/4 11:23
# @Version:     Python3.7
# @Description:
import os.path
import zipfile

import pandas as pd
from flask import Blueprint, request, send_file, send_from_directory
import io
from app.utils.response import success_response, error_response
from app.services.file_mgr_serv import FileMgrServ
from app.routes.auth import login_required


class FileMgrApi:
    """
    文件管理接口类
    """
    def __init__(self, logger, blueprint):
        self.logger = logger
        self.file_mgr_serv = FileMgrServ(logger)
        self.blueprint = blueprint
        self.register_blueprint()

    def register_blueprint(self):
        """注册文件管理相关的API路由"""
        self.blueprint.add_url_rule('/upload', view_func=self.upload, methods=['POST'])
        self.blueprint.add_url_rule('/download/<filename>', view_func=self.download, methods=['GET'])
        self.blueprint.add_url_rule('/image/<filename>', view_func=self.get_images, methods=['GET'])

    @login_required
    def get_images(self, filename):
        return self.file_mgr_serv.get_images(filename)

    @login_required
    def download(self, filename):
        """文件下载接口"""
        try:
            # 调用服务层获取文件
            success, result = self.file_mgr_serv.get_file(filename)
            if not success:
                return error_response(result, 404)
            
            # 返回文件内容
            return send_file(
                result,
                as_attachment=True,
                download_name=filename
            )
        except Exception as e:
            self.logger.error(f"文件下载失败: {str(e)}")
            return error_response("文件下载失败", 500)

    @login_required
    def upload(self):
        """文件上传接口"""
        try:
            self.logger.debug(f"接收上传请求，文件: {request.files}")
            if not request.files:
                return error_response("未上传文件", 400)

            file = next(iter(request.files.values()))
            if file.filename == '':
                return error_response("空文件名", 400)

            # 调用服务层处理上传
            success, result = self.file_mgr_serv.upload(file)
            if not success:
                return error_response(result, 400)
            return success_response({
                'errFiles': [],
                'succMap': {
                    file.filename: str(self.get_images(file.filename))
                }
            }, code=0)
        except Exception as e:
            self.logger.error(f"文件上传失败: {str(e)}")
            return error_response("文件上传失败", 500)